namespace ResponseLocalLibrary
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;
    using ASB.CC.Business;
    using ASBCC.Database.EntityFramework;
    using IAM.Interface.Model;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.UserManagement;
    using ASBCC.Business;
    using System.Configuration;

    public class ACIManagement
    {
        public ACMMode GetACIModel()
        {
            //string str = "CRApplicant|EVApplicant|COApplicant|CRCODStaff|EVCODStaff|COCODStaff|BusinessAdmin|CVApplicant|CVCODStaff|OCOBusinessAdmin|OCOApplicant|OCRMgr|OCVMgr|OCRStaff|OCVStaff|";
            string[] disableRoles = ConfigurationManager.AppSettings["Disable_Role"].Trim().ToLower().Split(';');
            ACSections sections = new ACSections();
            ACSection section = new ACSection();
            section.ID = "Role";
            sections.Items.Add(section);
            Dimensions dimensions = new Dimensions();
            Dimension dimension = new Dimension();
            dimension.ID = "Role";
            dimension.Display = "Role";
            dimension.Hierachical = false;
            dimension.MultiCheck = true;
            dimension.ACSection = section;
            dimension.DimensionLevels = new DimensionLevels();
            DimensionLevel level = new DimensionLevel();
            level.ID = "";
            level.Display = "";
            dimension.DimensionLevels.Items.Add(level);
            dimension.ACItems = new ACItems();
            foreach (var row in IAMHelper.GetRoleList())
            {
                ACItem item = new ACItem();
                item.DimensionLevel = level;
                item.ID = row.RoleID.ToString();
                item.Display = row.Name;
                if (row.IsAdmin)
                {
                    item.Attr3 = "1";
                }
                else
                {
                    bool disableFlag = false;
                    foreach (var disablerole in disableRoles)
                    {
                        if (disablerole == row.Name.Trim().ToLower())
                        {
                            disableFlag = true;
                            break;
                        }
                    }
                    if (disableFlag)
                        item.Attr3 = "2";
                    else
                        item.Attr3 = "0";
                }
                item.Parent = null;
                item.Attr1 = "None";
                item.Attr2 = row.BelongsTo;
                if (item.Display.ToLower() == "costcenterhead")
                {
                    item.Attr1 = "CostCenterHead";
                }
                //if (item.Display.ToLower() == "catdirector")
                //{
                //    item.Attr1 = "CATDirector";
                //}
                if (item.Display.ToLower() == "cio user")
                {
                    item.Attr1 = "Country";
                }
                dimension.ACItems.Items.Add(item);
            }
            Dimension dimension2 = new Dimension();
            dimension2.ID = "CostCenter";
            dimension2.Display = "CostCenter";
            dimension2.Hierachical = false;
            dimension2.MultiCheck = true;
            dimension2.ACSection = section;
            dimension2.DimensionLevels = new DimensionLevels();
            DimensionLevel level2 = new DimensionLevel();
            level2.ID = "";
            level2.Display = "";
            dimension2.DimensionLevels.Items.Add(level2);
            dimension2.ACItems = new ACItems();
            BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
            var costList = utility.BuildDicList("CostCenter-OCO");
            for (int i = 0; i < costList.Count; i++)
            {
                ACItem item2 = new ACItem();
                item2.ID = (costList[i] as DicItem).Id.ToString();
                item2.Display = (costList[i] as DicItem).DicItemKey.ToString();
                //item2.Display = row2["DicItemKey"].ToString();
                item2.DimensionLevel = level2;
                item2.Parent = null;
                dimension2.ACItems.Items.Add(item2);
            }
            Dimension dimension3 = new Dimension();
            dimension3.ID = "Country";
            dimension3.Display = "Country";
            dimension3.Hierachical = false;
            dimension3.MultiCheck = true;
            dimension3.ACSection = section;
            dimension3.DimensionLevels = new DimensionLevels();
            DimensionLevel level3 = new DimensionLevel();
            level3.ID = "";
            level3.Display = "";
            dimension3.DimensionLevels.Items.Add(level3);
            dimension3.ACItems = new ACItems();
            foreach (var row3 in IAMHelper.GetCountryList())
            {
                ACItem item4 = new ACItem();
                item4.ID = row3.RoleID.ToString();
                item4.Display = row3.Name.ToString();
                item4.DimensionLevel = level2;
                item4.Parent = null;
                item4.Attr1 = row3.Description;
                dimension3.ACItems.Items.Add(item4);
            }

            Dimension dimension4 = new Dimension();
            dimension4.ID = "CID Role";
            dimension4.Display = "CIS Domestic Role";
            dimension4.Hierachical = false;
            dimension4.MultiCheck = true;
            dimension4.ACSection = section;
            dimension4.DimensionLevels = new DimensionLevels();
            DimensionLevel level4 = new DimensionLevel();
            level4.ID = "";
            level4.Display = "";
            dimension4.DimensionLevels.Items.Add(level4);
            dimension4.ACItems = new ACItems();
            foreach (Cluster row4 in IAMHelper.GetAllClusters())
            {
                ACItem item5 = new ACItem();
                item5.ID = row4.ClusterID.ToString();
                item5.Display = row4.Name.ToString();
                item5.DimensionLevel = level2;
                item5.Parent = null;
                item5.Attr1 = "Cluster";
                dimension4.ACItems.Items.Add(item5);
            }
            foreach (Province row4 in IAMHelper.GetAllProvinces())
            {
                ACItem item5 = new ACItem();
                item5.ID = row4.ProvinceID.ToString();
                item5.Display = row4.Name.ToString() + "(" + row4.Description + ")";
                item5.DimensionLevel = level2;
                item5.Parent = null;
                item5.Attr1 = "Province";
                if (row4.Clusters.Count > 0)
                    item5.Attr2 = row4.Clusters.FirstOrDefault().ClusterID.ToString();
                dimension4.ACItems.Items.Add(item5);
            }
            foreach (Category row4 in IAMHelper.GetAllCategories())
            {
                ACItem item5 = new ACItem();
                item5.ID = row4.CateID.ToString();
                item5.Display = row4.Name.ToString();
                item5.DimensionLevel = level2;
                item5.Parent = null;
                item5.Attr1 = "Category";
                dimension4.ACItems.Items.Add(item5);
            }
            dimensions.Items.Add(dimension);
            dimensions.Items.Add(dimension2);
            dimensions.Items.Add(dimension3);
            dimensions.Items.Add(dimension4);
            ACMMode mode = new ACMMode();
            mode.MultiSection = false;
            mode.SectionList = sections;
            mode.DimensionList = dimensions;
            return mode;
        }

        public ACI GetUserACI(AccountInfo accountinfo)
        {
            ACI aci = new ACI();
            aci.AccountInfo = new AccountInfo();
            aci.AccountInfo.HRISEID = accountinfo.HRISEID;
            aci.AccountInfo.ADAccount = accountinfo.ADAccount;
            aci.AccountInfo.CSLAccount = accountinfo.CSLAccount;
            aci.AccountInfo.CILX500 = accountinfo.CILX500;
            aci.AccountInfo.UPI = accountinfo.UPI;
            aci.AccountInfo.AppAccount = accountinfo.AppAccount;
            aci.ACISessions = new ACISessions();
            try
            {
                List<ASBCC.Database.EntityFramework.Role> roles = IAMHelper.GetRoleByUserID(accountinfo.UPI);

                foreach (var role in roles)
                {
                    ACISession session = new ACISession();
                    CheckedItem item = new CheckedItem();
                    item.ACItemID = role.RoleID.ToString();
                    item.Attr1 = "role";
                    item.Attr2 = role.BelongsTo;
                    item.Attr3 = role.Name;
                    item.Value = true;
                    session.Items.Add(item);
                    if (role.Name.ToLower() == "costcenterhead")
                    {
                        BEGDC.CC.BL.UserManagement.IUser iuser = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                        DataTable costCenterUserRole = iuser.GetCostCenterByUserId(accountinfo.UPI);
                        for (int i = 0; i < costCenterUserRole.Rows.Count; i++)
                        {
                            CheckedItem item2 = new CheckedItem();
                            item2.ACItemID = costCenterUserRole.Rows[i]["CostCenterId"].ToString();
                            item2.Value = true;
                            item2.Attr1 = "costcenterhead";
                            item2.Attr2 = costCenterUserRole.Rows[i]["CostCenterCode"].ToString();
                            session.Items.Add(item2);

                        }
                    }
                    if (role.Name.ToLower() == "cio user")
                    {
                        foreach (var role1 in IAMHelper.GetCountryByUserID(accountinfo.UPI))
                        {
                            CheckedItem item3 = new CheckedItem();
                            item3.ACItemID = role1.RoleID.ToString();
                            item3.Value = true;
                            item3.Attr1 = "country";
                            item3.Attr2 = role1.Name;
                            session.Items.Add(item3);
                        }
                    }
                    aci.ACISessions.Items.Add(session);
                }
                ACISession session1 = new ACISession();
                bool sessionFlag = false;
                foreach (string roleDetail in RoleAssignmentHelper.GetUserRole(RoleAssignmentHelper.GetCILByEmployeeNo(accountinfo.UPI)).Split(','))
                {
                    string[] roleDetails = roleDetail.Split(';');
                    if (roleDetails == null || roleDetails.Count() == 0)
                        continue;
                    CheckedItem item4 = new CheckedItem();
                    item4.Value = true;
                    item4.Attr1 = "CIDRole";
                    if (roleDetails[0] == "Cluster")
                    {
                        item4.ACItemID = "Cluster";
                        item4.Attr4 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "Catvp")
                    {
                        item4.ACItemID = "Catvp";
                        item4.Attr3 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "CommercialP")
                    {
                        item4.ACItemID = "CommercialP";
                        item4.Attr2 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "CommercialC")
                    {
                        item4.ACItemID = "CommercialC";
                        item4.Attr3 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "DPSO")
                    {
                        item4.ACItemID = "DPSO";
                        item4.Attr2 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "PSO")
                    {
                        item4.ACItemID = "PSO";
                        item4.Attr2 = roleDetails[1];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                    if (roleDetails[0] == "Sales")
                    {
                        item4.ACItemID = "Sales";
                        item4.Attr2 = roleDetails[1];
                        item4.Attr3 = roleDetails[2];
                        session1.Items.Add(item4);
                        sessionFlag = true;
                        continue;
                    }
                }
                if (sessionFlag)
                    aci.ACISessions.Items.Add(session1);

                //for (int i = 0; i < roles.Count; i++)
                //{
                //BEGDC.CC.Entity.Role role = (BEGDC.CC.Entity.Role)roleByUserID[i];
                //ACISession session = new ACISession();
                //CheckedItem item = new CheckedItem();
                //item.ACItemID = role.Id.ToString();
                //item.Value = true;
                //session.Items.Add(item);
                //if (role.RoleName.ToLower() == "costcenterhead")
                //{
                //    DataTable costCenterHeadByUserRole = CCSFacade.GetCostCenterHeadByUserRole(accountinfo.UPI, role.RoleName);
                //    for (int j = 0; j < costCenterHeadByUserRole.Rows.Count; j++)
                //    {
                //        CheckedItem item2 = new CheckedItem();
                //        item2.ACItemID = "c_" + costCenterHeadByUserRole.Rows[j]["CostCenterID"].ToString();
                //        item2.Value = true;
                //        item2.Attr1 = "costcenterhead";
                //        session.Items.Add(item2);
                //    }
                //}
                //if (role.RoleName.ToLower() == "fnc")
                //{
                //    DataTable fNCDeptByUserRole = CCSFacade.GetFNCDeptByUserRole(accountinfo.UPI, role.RoleName);
                //    for (int k = 0; k < fNCDeptByUserRole.Rows.Count; k++)
                //    {
                //        CheckedItem item3 = new CheckedItem();
                //        item3.ACItemID = "f_" + fNCDeptByUserRole.Rows[k]["DepartmentID"].ToString();
                //        item3.Value = true;
                //        item3.Attr1 = "fnc";
                //        session.Items.Add(item3);
                //    }
                //}
                //if (role.RoleName.ToLower() == "catdirector")
                //{
                //    string catByUserRole = CCSFacade.GetCatByUserRole(accountinfo.UPI, role.RoleName);
                //    if (catByUserRole != string.Empty)
                //    {
                //        CheckedItem item4 = new CheckedItem();
                //        item4.ACItemID = "a_" + catByUserRole;
                //        item4.Attr1 = "catdirector";
                //        item4.Value = true;
                //        session.Items.Add(item4);
                //    }
                //}
                //aci.ACISessions.Items.Add(session);
                //}
            }
            catch (Exception)
            {
                aci.ACISessions = new ACISessions();
                ACISession session2 = new ACISession();
                CheckedItem item5 = new CheckedItem();
                item5.ACItemID = "Project Manager";
                item5.Value = true;
                session2.Items.Add(item5);
                CheckedItem item6 = new CheckedItem();
                item6.ACItemID = "G007";
                item6.Value = true;
                session2.Items.Add(item6);
                ACISession session3 = new ACISession();
                CheckedItem item7 = new CheckedItem();
                item7.ACItemID = "Department Manager";
                item7.Value = true;
                session3.Items.Add(item7);
                CheckedItem item8 = new CheckedItem();
                item8.ACItemID = "D010";
                item8.Value = true;
                session3.Items.Add(item8);
                CheckedItem item9 = new CheckedItem();
                item9.ACItemID = "上海";
                item9.Value = true;
                session3.Items.Add(item9);
                aci.ACISessions.Items.Add(session2);
                aci.ACISessions.Items.Add(session3);
            }
            return aci;
        }

        public ACI SetUserACI(ACI acifromrequest)
        {
            ACI userACI = new ACI();
            ACISession session = new ACISession();
            CheckedItem item = new CheckedItem();
            string roleID = string.Empty;
            try
            {
                List<int> ccsRoles = new List<int>();
                List<int> cisRoles = new List<int>();
                //define set cid roles input value
                string[] cidRoles = new string[] { "", "", "", "", "", "", "", "", "", "" };
                var allroles = IAMHelper.GetRoleList();
                BEGDC.CC.BL.Common.IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as BEGDC.CC.BL.Common.IUtility;
                var allcostList = utility.BuildDicList("CostCenter-OCO");
                var allCountry = IAMHelper.GetCountryList();
                int costcenter = 0;
                string costcenterRole = "";
                bool costcenterFlag = false;
                foreach (object obj2 in acifromrequest.ACISessions.Items)
                {
                    session = obj2 as ACISession;
                    if (session != null)
                    {
                        foreach (object obj3 in session.Items)
                        {
                            item = obj3 as CheckedItem;
                            if (item != null)
                            {
                                int roleID1 = 0;
                                int.TryParse(item.ACItemID, out roleID1);
                                switch (item.Attr1.ToLower().Trim())
                                {
                                    case "role":
                                        {
                                            if (allroles.Where(p => p.RoleID == roleID1).Count() == 0)
                                                return null;
                                            if (!costcenterFlag && IAMHelper.GetIsCostcernerHeadID() == int.Parse(item.ACItemID))
                                            {
                                                costcenterFlag = true;
                                                costcenter = roleID1;
                                                continue;
                                            }
                                            if (item.Attr2.ToLower() == "cco" || item.Attr2.ToLower() == "ccd")
                                                ccsRoles.Add(int.Parse(item.ACItemID));
                                            else if (item.Attr2.ToLower() == "cio")
                                                cisRoles.Add(int.Parse(item.ACItemID));
                                            else if (item.Attr2.ToLower() == "cid")
                                            {
                                                if (item.ACItemID == "11000")
                                                    cidRoles[0] = "1";
                                                else if (item.ACItemID == "11010")
                                                    cidRoles[1] = "1";
                                            }
                                            else
                                                return null;
                                            continue;
                                        }
                                    case "country":
                                        {
                                            if (allCountry.Where(p => p.RoleID == roleID1).Count() == 0)
                                                return null;
                                            cisRoles.Add(int.Parse(item.ACItemID));
                                            continue;
                                        }
                                    //case "catdirector":
                                    //    {
                                    //        CCSFacade.SaveUserRole_CAT(acifromrequest.AccountInfo.UPI, roleID, item.ACItemID);
                                    //        continue;
                                    //    }
                                    case "costcenterhead":
                                        {
                                            bool errorCheck = false;
                                            for (int i = 0; i < allcostList.Count; i++)
                                            {
                                                if ((allcostList[i] as DicItem).Id == roleID1)
                                                {
                                                    errorCheck = true;
                                                    break;
                                                }
                                            }
                                            if (!errorCheck)
                                                return null;
                                            costcenterRole += item.ACItemID + ",";
                                            continue;
                                        }
                                    case "cidrole":
                                        {
                                            switch (item.ACItemID.ToLower().Trim())
                                            {
                                                case "commercialp":
                                                    cidRoles[2] += item.Attr2 + ",";
                                                    continue;
                                                case "commercialc":
                                                    cidRoles[3] += item.Attr3 + ",";
                                                    continue;
                                                case "cluster":
                                                    cidRoles[4] += item.Attr4 + ",";
                                                    continue;
                                                case "catvp":
                                                    cidRoles[5] += item.Attr3 + ",";
                                                    continue;
                                                case "dpso":
                                                    cidRoles[6] += item.Attr2 + ",";
                                                    continue;
                                                case "pso":
                                                    cidRoles[7] += item.Attr2 + ",";
                                                    continue;
                                                case "sales":
                                                    cidRoles[8] += item.Attr2 + ",";
                                                    cidRoles[9] += item.Attr3 + ",";
                                                    continue;
                                            }
                                            continue;
                                        }
                                    default:
                                        {
                                            return null;
                                        }
                                }
                            }
                        }
                        continue;
                    }
                }
                if (!costcenterFlag)
                {
                    if (!String.IsNullOrEmpty(costcenterRole))
                        return null;
                }
                if (!cisRoles.Contains(12002))
                {
                    if (cisRoles.Count > 0)
                        return null;
                }

                RoleAssignmentHelper helper = new RoleAssignmentHelper();
                helper.SetUserRoles(acifromrequest.AccountInfo.UPI, ccsRoles, "CCD", true);
                helper.SetUserRoles(acifromrequest.AccountInfo.UPI, ccsRoles, "CCO", true);
                helper.SetUserRoles(acifromrequest.AccountInfo.UPI, cisRoles, "CIO", true);
                if (costcenterFlag)
                {
                    ccsRoles.Add(costcenter);
                    helper.SetUserRoles(acifromrequest.AccountInfo.UPI, ccsRoles, "CCD", true);
                    helper.SetUserRoles(acifromrequest.AccountInfo.UPI, ccsRoles, "CCO", true);
                    if (!String.IsNullOrEmpty(costcenterRole))
                    {
                        BEGDC.CC.BL.UserManagement.IUser iuser = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                        iuser.SaveCostCenterHeads(acifromrequest.AccountInfo.UPI, costcenter, costcenterRole.Substring(0, costcenterRole.Length - 1));
                    }
                }
                RoleAssignmentHelper.UpdateUser(cidRoles[0] == "1", cidRoles[1] == "1", cidRoles[2].ToString().TrimEnd(','), cidRoles[3].ToString().TrimEnd(','), cidRoles[4].ToString().TrimEnd(','), cidRoles[5].ToString().TrimEnd(','), cidRoles[6].ToString().TrimEnd(','), cidRoles[7].ToString().TrimEnd(','), cidRoles[8].ToString().TrimEnd(','), cidRoles[9].ToString().TrimEnd(','), RoleAssignmentHelper.GetCILByEmployeeNo(acifromrequest.AccountInfo.UPI));

                userACI = this.GetUserACI(acifromrequest.AccountInfo);
            }
            catch
            {
                return null;
                //userACI.ACISessions = new ACISessions();
                //ACISession session2 = new ACISession();
                //CheckedItem item2 = new CheckedItem();
                //item2.ACItemID = "Project Manager";
                //item2.Value = true;
                //session2.Items.Add(item2);
                //CheckedItem item3 = new CheckedItem();
                //item3.ACItemID = "G007";
                //item3.Value = true;
                //session2.Items.Add(item3);
                //ACISession session3 = new ACISession();
                //CheckedItem item4 = new CheckedItem();
                //item4.ACItemID = "Department Manager";
                //item4.Value = true;
                //session3.Items.Add(item4);
                //CheckedItem item5 = new CheckedItem();
                //item5.ACItemID = "D010";
                //item5.Value = true;
                //session3.Items.Add(item5);
                //CheckedItem item6 = new CheckedItem();
                //item6.ACItemID = "上海";
                //item6.Value = true;
                //session3.Items.Add(item6);
                //userACI.ACISessions.Items.Add(session2);
                //userACI.ACISessions.Items.Add(session3);
            }
            return userACI;
        }
    }
}

